﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using log4net;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;

namespace Matrix.MaKaYunShang.ApiService.Controllers
{
    /// <summary>
    /// 商品信息API
    /// </summary>
    public class CommodityApiController : BaseApiController
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(CommodityApiController));
        private readonly ShopCommodityBLL _shopCommodityBll = new ShopCommodityBLL();
        private readonly CommodityLibBLL _commodityLibBll = new CommodityLibBLL();
        private readonly CommodityCategoryBLL _commodityCategoryBll = new CommodityCategoryBLL();

        //POST api/CommodityApi/GetCommodityListOnSell/
        /// <summary>
        /// 根据商铺ID以及商品分类ID获取上架商品列表
        /// </summary>
        /// <param name="shopId">商铺ID</param>
        /// <param name="cateId">商品分类ID</param>
        /// <returns>返回店铺商品DTO列表（含图片、赠品以及店铺售卖信息）</returns>
        [HttpPost]
        public Result<List<ShopCommodityDto>> GetCommodityListOnSell(int shopId, int cateId)
        {
            var checkResult = CheckPermission("CommodityApiController | GetCommodityListOnSell");
            if (!checkResult.Status)
            {
                return new Result<List<ShopCommodityDto>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
             }
            if (shopId <= 0 || cateId <= 0)
            {
                _fileLog.Error("CommodityApiController | GetCommodityListOnSell | Error: Empty paramter.");
                return new Result<List<ShopCommodityDto>>
                {
                    Status = false,
                    Message = "Empty paramter.",
                    Data = null
                };
            }
            try
            {
                var lsShopCommodity = _shopCommodityBll.GetShopCommodityList(shopId, cateId, 1);
                if (lsShopCommodity == null || lsShopCommodity.Count == 0)
                {
                    return new Result<List<ShopCommodityDto>>
                    {
                        Status = true,
                        Message = "No commodity on sell in this shop.",
                        Data = new List<ShopCommodityDto>()
                    };
                }
                var lsShopCommodityDto = new List<ShopCommodityDto>(); 
                foreach (var shopCommodity in lsShopCommodity)
                {
                    var shopCommodityDto = new ShopCommodityDto {ShopCommodityInfo = shopCommodity};
                    var commodityDto = _commodityLibBll.GetCommodityFullInfo(shopCommodity.CommodityLibId);
                    if (commodityDto == null) continue;
                    shopCommodityDto.BaseCommodityInfo = commodityDto.BaseCommodityInfo;
                    shopCommodityDto.PictureList = commodityDto.PictureList;
                    shopCommodityDto.GiftList = commodityDto.GiftList;
                    lsShopCommodityDto.Add(shopCommodityDto);
                }

                return new Result<List<ShopCommodityDto>>
                {
                    Status = true,
                    Message = "Success",
                    Data = lsShopCommodityDto
                };

            }
            catch (Exception ex)
            {
                _fileLog.Error("CommodityApiController | GetCommodityListOnSell | Exception: " + ex.Message + ex.StackTrace);
                return new Result<List<ShopCommodityDto>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        //POST api/CommodityApi/GetCommodityCategoryList/
        /// <summary>
        /// 根据商铺ID获取上架商品分类列表
        /// </summary>
        /// <param name="shopId">商铺ID</param>
        /// <returns>返回商品分类列表</returns>
        [HttpPost]
        public Result<List<CommodityCategory>> GetCommodityCategoryList(int shopId)
        {
            var checkResult = CheckPermission("CommodityApiController | GetCommodityCategoryList");
            if (!checkResult.Status)
            {
                return new Result<List<CommodityCategory>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }

            if (shopId <= 0)
            {
                _fileLog.Error("CommodityApiController | GetCommodityCategoryList | Error: Empty paramter.");
                return new Result<List<CommodityCategory>>
                {
                    Status = false,
                    Message = "Empty paramter.",
                    Data = null
                };
            }

            try
            {
                var lsCategory = _commodityCategoryBll.GetCateListByShopId(shopId, true);
                return new Result<List<CommodityCategory>>
                {
                    Status = true,
                    Message = "Success",
                    Data = lsCategory
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("CommodityApiController | GetCommodityCategoryList | Exception: " + ex.Message + ex.StackTrace);
                return new Result<List<CommodityCategory>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        //POST api/CommodityApi/GetShopCommodityInfo/
        /// <summary>
        /// 根据店铺商品ID获取上架商品信息
        /// </summary>
        /// <param name="shopCommodityId">店铺商品ID</param>
        /// <returns>返回店铺商品信息（含图片、赠品以及店铺售卖信息）</returns>
        [HttpPost]
        public Result<ShopCommodityDto> GetShopCommodityInfo(int shopCommodityId)
        {
            var checkResult = CheckPermission("CommodityApiController | GetShopCommodityInfo");
            if (!checkResult.Status)
            {
                return new Result<ShopCommodityDto>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }

            if (shopCommodityId <= 0)
            {
                _fileLog.Error("CommodityApiController | GetShopCommodityInfo | Error: Empty paramter.");
                return new Result<ShopCommodityDto>
                {
                    Status = false,
                    Message = "Empty paramter.",
                    Data = null
                };
            }

            try
            {
                var shopCommodityInfo = _shopCommodityBll.GetModel(shopCommodityId);
                if (shopCommodityInfo == null || shopCommodityInfo.Id == 0)
                {
                    return new Result<ShopCommodityDto>
                    {
                        Status = false,
                        Message = "Cannot find the commodity info in database",
                        Data = null
                    };
                }

                var commodityFullInfo = _commodityLibBll.GetCommodityFullInfo(shopCommodityInfo.CommodityLibId);
                if (commodityFullInfo == null || commodityFullInfo.BaseCommodityInfo == null ||
                    commodityFullInfo.BaseCommodityInfo.Id == 0)
                {
                    return new Result<ShopCommodityDto>
                    {
                        Status = false,
                        Message = "Cannot find the commodity info in database",
                        Data = null
                    };
                }

                var shopCommodityDto = new ShopCommodityDto
                {
                    ShopCommodityInfo = shopCommodityInfo,
                    BaseCommodityInfo = commodityFullInfo.BaseCommodityInfo,
                    PictureList = commodityFullInfo.PictureList,
                    GiftList = commodityFullInfo.GiftList
                };

                return new Result<ShopCommodityDto>
                {
                    Status = true,
                    Message = "Success",
                    Data = shopCommodityDto
                };

            }
            catch (Exception ex)
            {
                _fileLog.Error("CommodityApiController | GetShopCommodityInfo | Exception: " + ex.Message + ex.StackTrace);
                return new Result<ShopCommodityDto>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        //POST api/CommodityApi/GetCommodityFullInfoOfAppointedIds/
        /// <summary>
        /// 根据逗号分隔的商品ID集合获取商品全信息列表
        /// </summary>
        /// <param name="shopCommodityIds">逗号分隔的商品ID集合</param>
        /// <param name="shopId">店铺ID</param>
        /// <param name="consumerId">用户ID</param>
        /// <param name="verifyCode">加密字符串</param>
        /// <returns>返回店铺商品信息列表（含图片、赠品以及店铺售卖信息）</returns>
        [HttpPost]
        public Result<List<ShopCommodityDto>> GetCommodityFullInfoOfAppointedIds(string shopCommodityIds, int shopId, int consumerId, string verifyCode)
        {
            #region 合法性校验
            var checkResult = CheckPermission("CommodityApiController | GetCommodityFullInfoOfAppointedIds");
            if (!checkResult.Status)
            {
                return new Result<List<ShopCommodityDto>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }

            if (string.IsNullOrWhiteSpace(shopCommodityIds))
            {
                _fileLog.Error("CommodityApiController | GetCommodityFullInfoOfAppointedIds | Error: Empty paramter.");
                return new Result<List<ShopCommodityDto>>
                {
                    Status = false,
                    Message = "Empty paramter.",
                    Data = null
                };
            }

            var checkVerifyCode = EncryptionLib.Encrypt(shopCommodityIds + shopId + consumerId);
            if (checkVerifyCode != verifyCode)
            {
                _fileLog.Error("CommodityApiController | GetCommodityFullInfoOfAppointedIds | Error: Invalid verify code.");
                return new Result<List<ShopCommodityDto>>
                {
                    Status = false,
                    Message = "Invalid verify code",
                    Data = null
                };
            }
            #endregion

            try
            {
                var lsShopCommodity = _shopCommodityBll.GetShopCommodityListAppointedIds(shopId, shopCommodityIds);
                if (lsShopCommodity == null || lsShopCommodity.Count == 0)
                {
                    return new Result<List<ShopCommodityDto>>
                    {
                        Status = false,
                        Message = "Cannot find the commodity info in database.Step 1",
                        Data = null
                    };
                }

                var strCommodityIds = string.Join(",", lsShopCommodity.Select(p=>p.CommodityLibId));
                if (string.IsNullOrWhiteSpace(strCommodityIds))
                {
                    return new Result<List<ShopCommodityDto>>
                    {
                        Status = false,
                        Message = "Cannot find the commodity info in database.Step 2",
                        Data = null
                    };
                }

                var lsCommodityDto = _commodityLibBll.GetCommodityFullInfoAppointedIds(strCommodityIds);
                if (lsCommodityDto == null || lsCommodityDto.Count == 0)
                {
                    return new Result<List<ShopCommodityDto>>
                    {
                        Status = false,
                        Message = "Cannot find the commodity info in database.Step 3",
                        Data = null
                    };
                }

                var lsShopCommodityDto = new List<ShopCommodityDto>();
                foreach (var shopCommodity in lsShopCommodity)
                {
                    var commodityDto = lsCommodityDto.FirstOrDefault(p => p.BaseCommodityInfo.Id == shopCommodity.CommodityLibId);
                    if (commodityDto != null)
                    {
                        var giftList = new List<CommodityGift>();
                        if (commodityDto.GiftList != null && commodityDto.GiftList.Count > 0)
                        {
                            foreach (var gift in commodityDto.GiftList)
                            {
                                var timeSpanList = TimeHelper.GetTimeRangeByTimeSpanType((TimeSpanType)gift.TimeSpanType, gift.TimeSpanCount);
                                var giftCount = OrderDetailBLL.Instance.GetOrderGiftCountByTime(consumerId, gift.Id, timeSpanList[0].ToString(), timeSpanList[1].ToString());
                                if (giftCount < gift.ConsumerGetTotalTimes)
                                {
                                    giftList.Add(gift);
                                }
                            }
                        }
                        lsShopCommodityDto.Add(new ShopCommodityDto
                        {
                            ShopCommodityInfo = shopCommodity,
                            BaseCommodityInfo = commodityDto.BaseCommodityInfo,
                            PictureList = commodityDto.PictureList,
                            GiftList = giftList
                        });
                    }
                }


                return new Result<List<ShopCommodityDto>>
                {
                    Status = true,
                    Message = "Success",
                    Data = lsShopCommodityDto
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("CommodityApiController | GetCommodityFullInfoOfAppointedIds | Exception: " + ex.Message +
                               ex.StackTrace);
                return new Result<List<ShopCommodityDto>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        /// <summary>
        /// 行业列表
        /// </summary>
        /// <returns>返回商品分类列表</returns>
        [HttpPost]
        public Result<List<Industry>> GetCommodityIndustryList()
        {
            var checkResult = CheckPermission("CommodityApiController | GetCommodityIndustryList");
            if (!checkResult.Status)
            {
                return new Result<List<Industry>>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            try
            {
                var industry = IndustryBLL.Instance.GetModelList("");
                return new Result<List<Industry>>
                {
                    Status = true,
                    Message = "Success",
                    Data = industry
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("CommodityApiController | GetCommodityIndustryList | Exception: " + ex.Message + ex.StackTrace);
                return new Result<List<Industry>>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

    }
}
